package com.wibo.account;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import weibo4android.Comment;
import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
import com.wibo.common.HScrollViewGroup;
import com.wibo.common.CommentItem;
import com.wibo.common.Constants;
import com.wibo.common.FileDbHelper;
import com.wibo.common.Utility;
import com.wibo.common.WeiboItem;
import com.wibo.common.HScrollViewGroup.OnItemSelectedListener;
import com.wibo.service.IWeiboService;
import com.wibo.service.IWeiboServiceCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class WiboTabActivity extends /*Tab*/Activity implements OnTouchListener, OnGestureListener, OnScrollListener, OnItemSelectedListener, OnClickListener, OnItemClickListener {
	
	public static final String TAG = "WiboTabActivity";
	private static Weibo mWeibo = null;
	private static OAuthConstant mAuthConstant = null;
	private static User mUser = null;
	protected FileDbHelper mDbHelper = null;
	//private TabHost mTabHost;
	private HScrollViewGroup mListContentView;
	private int mCurrentScreen = TYPE_ALL;
	private RelativeLayout mScrollbarTipLayout;
	
	private static final int TYPE_ALL = 0;
	private static final int TYPE_FREE = 1;
	private static final int TYPE_PAY = 2;
	
	
//	private LinearLayout mCommentsLayout;
//	private LinearLayout mTransmitsLayout;
//	private LinearLayout mPrivateLayout;
	
	private View mBottomViewComments = null;
	private View mBottomViewTransmits = null;
	//private View mBottomViewPrivate = null;
	
	private TextView mTextViewComment = null;
	private TextView mTextViewTransmits = null;
	//private TextView mTextViewPrivate = null;
	
	private PullToRefreshListView mCommentsList;
	private View mLvfooterComment = null;
	private ProgressBar mFooterProComment = null;
	
	private PullToRefreshListView mTransmitsList;
	private View mLvfooterTransmit = null;
	private ProgressBar mFooterProTransmit = null;
	//private ListView mPrivateList;
	private long mNewestCommentId = -1;
	private long mOldestCommentId = -1;
	
	private long mNewestTransmitId = -1;
	private long mOldestTransmitId = -1;
	
	private ArrayList<CommentItem> mCommentsListData;
	private ArrayList<WeiboItem> mTransmitsListData;
	private CommentListItemAdapter mCommentsListAdapter;
	private WeiboListItemAdapter mTransmitsListAdapter;
/*	private ListView mTransmitsList;
	private ListView mPrivateMsgList;*/
	
	private static final int MAX_SAVE_COUNT = 60;
	
	private static final int SHOW_NEW_COMMENTS = 1;
	private static final int SHOW_NEW_COMMENTS_ERROR = -1;
	private static final int SHOW_BUTTOM_COMMENTS = 2;
	private static final int SHOW_BUTTOM_COMMENTS_ERROR = 9;
	private static final int SHOW_TOP_COMMENTS = 3;
	
	private static final int SHOW_COMMENT_FROM_DATABASE = 4;
	private static final int SHOW_NEW_TRANSMITS = 5;
	private static final int SHOW_NEW_TRANSMITS_ERROR = -5;
	private static final int SHOW_BUTTOM_TRANSMITS = 6;
	private static final int SHOW_BUTTOM_TRANSMITS_ERROR = 10;
	private static final int SHOW_TOP_TRANSMITS = 7;
	private static final int SHOW_TRANSMIT_FROM_DATABASE = 8;
	
	private static final int REFRESH_COMMENT_LIST = 50;
	private static final int REFRESH_TRANSMIT_LIST = 51;
	//private static final int SHOW_NEW_COMMENTS = 1;
	
	public static final String COMMENT_NEWEST_ID = "CommentNewestId";
	public static final String COMMENT_OLDEST_ID = "CommentOldestId";
	
	public static final String TRANSMIT_NEWEST_ID = "TransmitNewestId";
	public static final String TRANSMIT_OLDEST_ID = "TransmitOldestId";
	
	//private LinearLayout mLoadingLayout;
	//private TextView mNoResultText; 
	
	GestureDetector mGestureDetector;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SHOW_NEW_COMMENTS:
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
				
				try {
					if (mWeiboService != null) {
						mWeiboService.resetCount(1);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				mCommentsListAdapter.notifyDataSetChanged();
				
				mCommentsList.onRefreshComplete();
				if (mCommentsListData.size() > 0) {
//					mCommentsList.setVisibility(ListView.VISIBLE);
					mCommentsList.setSelection(1);
//					mNoResultText.setVisibility(View.GONE);
					mLvfooterComment.setVisibility(View.VISIBLE);
				}else{
//					mCommentsList.setVisibility(ListView.INVISIBLE);
//					mNoResultText.setVisibility(View.VISIBLE);
					mLvfooterComment.setVisibility(View.GONE);
				}
				Intent intent = new Intent();
				intent.setAction(WiboMainTabActivity.CLEAN_COMMENTS_ACTION);
				sendBroadcast(intent);
				
				if (msg.arg2 > 0)
					Toast.makeText(WiboTabActivity.this, msg.arg2 + getString(R.string.newCommentCount), Toast.LENGTH_SHORT).show();
				loadImageDrawable(msg.arg1, 0);
				
				break;
			case REFRESH_COMMENT_LIST:
				
				mCommentsListAdapter.notifyDataSetChanged();
				mFooterProComment.setVisibility(ProgressBar.INVISIBLE);
				break;
			case SHOW_NEW_COMMENTS_ERROR:
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
//				if (mCommentsListData.size() > 0) {
//					mCommentsList.setVisibility(ListView.VISIBLE);
//				}else{
//					mCommentsList.setVisibility(ListView.INVISIBLE);
//				}
				mCommentsList.onRefreshComplete();
				Toast.makeText(WiboTabActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				break;
			
			case REFRESH_TRANSMIT_LIST:
				mTransmitsListAdapter.notifyDataSetChanged();
				mFooterProTransmit.setVisibility(ProgressBar.INVISIBLE);
				break;
			case SHOW_COMMENT_FROM_DATABASE:
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
				if (msg.obj != null) {
					ArrayList<CommentItem> itemDataList = (ArrayList<CommentItem>)msg.obj;
					
					mCommentsListData.clear();
					mCommentsListData.addAll(itemDataList);
					mCommentsList.onRefreshComplete();
					mCommentsListAdapter.notifyDataSetChanged();
					if (mCommentsListData.size() > 0) {
//						mCommentsList.setVisibility(ListView.VISIBLE);
						mCommentsList.setSelection(1);
//						mNoResultText.setVisibility(View.GONE);
						mLvfooterComment.setVisibility(View.VISIBLE);
					}else{
//						mCommentsList.setVisibility(ListView.INVISIBLE);
//						mNoResultText.setVisibility(View.VISIBLE);
						mLvfooterComment.setVisibility(View.GONE);
					}
					loadImageDrawable(msg.arg1, 0);
				}
				break;
			case SHOW_NEW_TRANSMITS:
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
				mTransmitsListAdapter.notifyDataSetChanged();
				mTransmitsList.onRefreshComplete();
				try {
					if (mWeiboService != null) {
						mWeiboService.resetCount(2);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				
				loadImageDrawable(msg.arg1, 0);
				if (mTransmitsListData.size() > 0) {
//					mTransmitsList.setVisibility(ListView.VISIBLE);
					mTransmitsList.setSelection(1);
//					mNoResultText.setVisibility(View.GONE);
					mLvfooterTransmit.setVisibility(View.VISIBLE);
				}else{
//					mTransmitsList.setVisibility(ListView.INVISIBLE);
//					mNoResultText.setVisibility(View.VISIBLE);
					mLvfooterTransmit.setVisibility(View.GONE);
				}
				intent = new Intent();
				intent.setAction(WiboMainTabActivity.CLEAN_TRANSMITS_ACTION);
				sendBroadcast(intent);
				
				if (msg.arg2 > 0)
					Toast.makeText(WiboTabActivity.this, msg.arg2 + getString(R.string.newTransmitCount), Toast.LENGTH_SHORT).show();
				break;
				
			case SHOW_NEW_TRANSMITS_ERROR:
				mTransmitsList.onRefreshComplete();
				Toast.makeText(WiboTabActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				break;	
			case SHOW_TRANSMIT_FROM_DATABASE:
				
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
				if (msg.obj != null) {
					ArrayList<WeiboItem> itemDataList = (ArrayList<WeiboItem>)msg.obj;
					mTransmitsListData.clear();
					mTransmitsListData.addAll(itemDataList);
					mTransmitsListAdapter.notifyDataSetChanged();
					mTransmitsList.onRefreshComplete();
					if (mTransmitsListData.size() > 0) {
//						mTransmitsList.setVisibility(ListView.VISIBLE);
						mTransmitsList.setSelection(1);
//						mNoResultText.setVisibility(View.GONE);
						mLvfooterTransmit.setVisibility(View.VISIBLE);
					}else{
//						mTransmitsList.setVisibility(ListView.INVISIBLE);
//						mNoResultText.setVisibility(View.VISIBLE);
						mLvfooterTransmit.setVisibility(View.GONE);
					}
					loadImageDrawable(msg.arg1, 0);
				}
				break;
			case SHOW_BUTTOM_COMMENTS:
				mCommentsListAdapter.notifyDataSetChanged();
				mFooterProComment.setVisibility(ProgressBar.INVISIBLE);
				break;
			case SHOW_BUTTOM_COMMENTS_ERROR:
				mFooterProComment.setVisibility(ProgressBar.INVISIBLE);
				Toast.makeText(WiboTabActivity.this, getString(R.string.getFailed), Toast.LENGTH_SHORT).show();
				break;
			case SHOW_BUTTOM_TRANSMITS:
				mTransmitsListAdapter.notifyDataSetChanged();
				mFooterProTransmit.setVisibility(ProgressBar.INVISIBLE);
				break;
			case SHOW_BUTTOM_TRANSMITS_ERROR:
				mFooterProTransmit.setVisibility(ProgressBar.INVISIBLE);
				Toast.makeText(WiboTabActivity.this, getString(R.string.getFailed), Toast.LENGTH_SHORT).show();
				break;
			}
			
		}
	};

	private void sendMessageDelayed2(int what, int delayMillis) {
		Message msg = mHandler.obtainMessage(what);
		mHandler.sendMessageDelayed(msg, delayMillis);
	}

	private void sendMessage(int what, Object obj) {
		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
	private void sendMessage(int what, int arg1, int arg2, Object obj) {
		Message msg = mHandler.obtainMessage(what, arg1, arg2, obj);
		mHandler.sendMessage(msg);
	}
	
	private IWeiboService mWeiboService = null;
	
	private ServiceConnection mAccountConnection = new ServiceConnection() {
		
		public void onServiceDisconnected(ComponentName name) {
			mWeiboService = null;
			
		}
		
		public void onServiceConnected(ComponentName name, IBinder service) {
			mWeiboService = IWeiboService.Stub.asInterface(service);
			try{
				mWeiboService.registerCallback(mWeiboServiceCallback);
			}catch(RemoteException e){
				e.printStackTrace();
			}
			
		}
	};
	
	private IWeiboServiceCallback.Stub mWeiboServiceCallback = new IWeiboServiceCallback.Stub() {
		
		@Override
		public void unreadWeibo(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadTransmit(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadFans(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadComment(long count) throws RemoteException {
		}

		@Override
		public void haveNewWeibo(boolean isHave) throws RemoteException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void unreadTotalMessages(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
	};
	
	private boolean bindWeiboService() {
		Intent serviceIntent = new Intent();
		serviceIntent.setAction("com.wibo.service.WeiboService");
		ComponentName name = getApplicationContext().startService(serviceIntent);
		if (name == null) {
			return false;
		}
		boolean isSuc = getApplicationContext().bindService(serviceIntent, mAccountConnection, Context.BIND_AUTO_CREATE);
		
		return isSuc;
	}
	
	private void setContentViewSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			setContentView(R.layout.wibotabs);
			break;
		case 1:
			setContentView(R.layout.wibotabs_2);
			break;
		default:
			setContentView(R.layout.wibotabs);
			break;
		}
	}
	
	private int getListFooterSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			return R.layout.weibofooter;
		case 1:
			return R.layout.weibofooter_2;
		default:
			return R.layout.weibofooter;
		}
	}
	
	private CUserManager mUserManager = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mUserManager = CUserManager.getInstance(this);
        
        setContentViewSkin();
//        mTabHost = getTabHost();
        
        //LayoutInflater.from(this).inflate(R.layout.wibotabs, tabHost.getTabContentView(), true);
        if (mDbHelper == null)
			mDbHelper = new FileDbHelper(this);

//        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("tab1").setContent(R.id.commentsList));
//        
//        mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("tab2").setContent(R.id.transmitsList));
//        
//        mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("tab3").setContent(R.id.privateMsgList));
        
        mListContentView = (HScrollViewGroup) findViewById(R.id.listContent);
        mListContentView.setOnItemSelectedListener(this);
        
        mScrollbarTipLayout = (RelativeLayout) findViewById(R.id.scrollbarTipLayout);
        
        //mCommentsLayout = (LinearLayout) findViewById(R.id.AppAllLiLayout);
        
		if (mAuthConstant == null)
			mAuthConstant = OAuthConstant.getInstance();

		if (mWeibo == null)
			mWeibo = mAuthConstant.getWeibo();
		
		mWeibo.setToken(mAuthConstant.getToken(), mAuthConstant
				.getTokenSecret());
		
//		mLoadingLayout = (LinearLayout) findViewById(R.id.LoadingLayout);
//		mNoResultText = (TextView) findViewById(R.id.NoResultText);
		
        
        mCommentsList = (PullToRefreshListView) findViewById(R.id.commentsList);
        mLvfooterComment = LayoutInflater.from(WiboTabActivity.this).inflate(getListFooterSkin(), null);	
		
		if(mLvfooterComment != null){
			mFooterProComment = (ProgressBar) mLvfooterComment.findViewById(R.id.moreWeiboProgress);
			mFooterProComment.setVisibility(ProgressBar.INVISIBLE);
			mLvfooterComment.setVisibility(View.INVISIBLE);

			mCommentsList.addFooterView(mLvfooterComment);
			mCommentsList.setFooterDividersEnabled(true);
			mLvfooterComment.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//Toast.makeText(WiboTabActivity.this, "~~~~", Toast.LENGTH_SHORT).show();
					if (!Utility.isNetworkAvailable(WiboTabActivity.this)){
						Toast.makeText(WiboTabActivity.this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
						return;
					}
					getMoreComment(mCommentsListData.get(mCommentsListData.size()-1).getId());
					//getMoreWeibo(mItemDataList.get(mItemDataList.size()-1).getmWeiboId());
				}
			});
		}
//		mCommentsList.setVisibility(ListView.INVISIBLE);
		
        mTransmitsList = (PullToRefreshListView) findViewById(R.id.transmitsList);
        mTransmitsList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				showTransmitItemDialog(arg2 - 1);
				return false;
			}
		});
        
        mLvfooterTransmit = LayoutInflater.from(WiboTabActivity.this).inflate(getListFooterSkin(), null);	
		
		if(mLvfooterTransmit != null){
			mFooterProTransmit = (ProgressBar) mLvfooterTransmit.findViewById(R.id.moreWeiboProgress);
			mFooterProTransmit.setVisibility(ProgressBar.INVISIBLE);
			mLvfooterTransmit.setVisibility(View.INVISIBLE);

			mTransmitsList.addFooterView(mLvfooterTransmit);
			mTransmitsList.setFooterDividersEnabled(true);
			mLvfooterTransmit.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//Toast.makeText(WiboTabActivity.this, "~~~~", Toast.LENGTH_SHORT).show();
					if (!Utility.isNetworkAvailable(WiboTabActivity.this)){
						Toast.makeText(WiboTabActivity.this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
						return;
					}
					getMoreTransmit(mTransmitsListData.get(mTransmitsListData.size()-1).getmWeiboId());
					//getMoreWeibo(mItemDataList.get(mItemDataList.size()-1).getmWeiboId());
				}
			});
		}
//		mTransmitsList.setVisibility(ListView.INVISIBLE);
        //mPrivateList = (ListView) findViewById(R.id.privateMsgList);
        
        mCommentsList.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                //new GetDataTask().execute();
            	if (Utility.isNetworkAvailable(WiboTabActivity.this))
            		getNewComments();
            }
        });
        mCommentsList.setSelected(true);
        mCommentsList.setOnItemClickListener(this);
        
        mTransmitsList.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                //new GetDataTask().execute();
            	if (Utility.isNetworkAvailable(WiboTabActivity.this))
            		getNewTransmits();
            }
        });
        mTransmitsList.setSelected(true);
        mTransmitsList.setOnItemClickListener(this);
        
        // 添加手势
        mGestureDetector = new GestureDetector(this);

        //mCommentsList.setOnTouchListener(this);
        mCommentsList.setLongClickable(true);
        //mCommentsList.setSelected(true);
        //mTransmitsList.setOnTouchListener(this);
        mTransmitsList.setLongClickable(true);
        //mTransmitsList.setSelected(true);
        //mPrivateList.setOnTouchListener(this);
        //mPrivateList.setLongClickable(true);
        //mPrivateList.setSelected(true);
        
        mCommentsListData = new ArrayList<CommentItem>();
        mCommentsListAdapter = new CommentListItemAdapter(this);
        mCommentsListAdapter.setAdapterData(mCommentsListData);
        mCommentsList.setAdapter(mCommentsListAdapter);
        mCommentsList.setOnScrollListener(this);
        
        mTransmitsListData = new ArrayList<WeiboItem>();
        mTransmitsListAdapter = new WeiboListItemAdapter(this);
        mTransmitsListAdapter.setAdapterData(mTransmitsListData);
        mTransmitsList.setAdapter(mTransmitsListAdapter);
        mTransmitsList.setOnScrollListener(this);
        
        if (!Utility.isNetworkAvailable(this)){
			Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
		 }
        initHeaderBar();
        setUiShow(TYPE_ALL, /*true, */false);
        
        bindWeiboService();
        
        IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(WiboMainTabActivity.NOTIFICATION_FRESH_COMMENTS);
		intentFilter.addAction(WiboMainTabActivity.NOTIFICATION_FRESH_TRANSMITS);
      	registerReceiver(mNotificationBroadcast, intentFilter);
        
        getCommentListFromDatabase();
    }
    
 // 初始化header
    private void initHeaderBar(){
  
        FrameLayout selectLayout = (FrameLayout)findViewById(R.id.commentTitleHelpLayout);
        selectLayout.setSelected(true);
    
        selectLayout = (FrameLayout)findViewById(R.id.transmitTitleHelpLayout);
        selectLayout.setSelected(true);
     
//        selectLayout = (FrameLayout)findViewById(R.id.privateTitleHelpLayout);
//        selectLayout.setSelected(true);
//        selectLayout.setVisibility(FrameLayout.GONE);

        Button btnAllTop = (Button) findViewById(R.id.commentTitleBtn);
        Button btnFreeTop = (Button) findViewById(R.id.transmitTitleBtn);
        //Button btnPayTop = (Button) findViewById(R.id.privateTitleBtn);
        
        btnAllTop.setOnClickListener(this);
        btnFreeTop.setOnClickListener(this);
        //btnPayTop.setOnClickListener(this);
        
        mTextViewComment = (TextView) findViewById(R.id.commentTitleText);
        mTextViewTransmits = (TextView) findViewById(R.id.transmitTitleText);
        //mTextViewPrivate = (TextView) findViewById(R.id.privateTitleText);
    }
    
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
        SharedPreferences.Editor editor = lastPreferences.edit();
        editor.putInt(Constants.PREFERENCE_RECORD, 1);
        editor.commit();
	}

	@Override
	protected void onPause() {
		Activity parent = getParent();
        if(parent != null) {
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 1);
            editor.commit();
            
        } else {       	
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 1);
            editor.commit();
            
        }
		super.onPause();
	}
	
	@Override
	public void onBackPressed() {
        Activity parent = getParent();
        if(parent != null) {
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 1);
            editor.commit();
            
            parent.onBackPressed();
        } else {       	
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 1);
            editor.commit();
            
            super.onBackPressed();
        }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, getString(R.string.refreshWeibo))/*.setIcon(
				R.drawable.ic_menu_edit_password)*/;
//		menu.add(0, 1, 1, getString(R.string.newWeibo))/*.setIcon(
//				R.drawable.ic_menu_exit)*/;
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case 0:
			if (!Utility.isNetworkAvailable(this)){
				Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
				return false;
			}
			switch (/*mTabHost.getCurrentTab()*/mCurrentScreen){
			case 0:
				getNewComments();
				break;
			case 1:
				getNewTransmits();
				break;
			case 2:
				break;
			}
			
			break;
//		case 1:
//			if (!Utility.isNetworkAvailable(this)){
//				Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
//				return false;
//			}
//			
//			Intent intent = new Intent(WiboMainActivity.this,
//					SendWeiboActivity.class);
//			startActivity(intent);
//			break;
			
		}
		return false;
	}
	
	
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		try{
			unregisterReceiver(mNotificationBroadcast);
		}catch(Exception e){
			
		}
		
		if (mGetNewCommentsThread != null) {
			if (mGetNewCommentsThread.isAlive()) {
				mGetNewCommentsThread.interrupt();
			}
			mGetNewCommentsThread = null;
			mIsGettingNewComments = false;
		}
		
		if (mThreadGetFromDatabase != null) {
			if (mThreadGetFromDatabase.isAlive()) {
				mThreadGetFromDatabase.interrupt();
			}
			mThreadGetFromDatabase = null;
			isGettingFromDatabase = false;
		}
		
		if (mGetNewTransmitsThread != null) {
			if (mGetNewTransmitsThread.isAlive()) {
				mGetNewTransmitsThread.interrupt();
			}
			mGetNewTransmitsThread = null;
			mIsGettingNewTransmits = false;
		}
		
		if(mWeiboService != null){
			try{
				getApplicationContext().unbindService(mAccountConnection);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				mWeiboService = null;
			}
		}
	}

	private final BroadcastReceiver mNotificationBroadcast = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(WiboMainTabActivity.NOTIFICATION_FRESH_COMMENTS)){
				//Log.i(TAG, "BroadcastReceiver :" + WiboMainTabActivity.NOTIFICATION_FRESH_COMMENTS);
				onClick((Button) findViewById(R.id.commentTitleBtn));
				if (mGetNewCommentsThread != null) {
					if (!mGetNewCommentsThread.isAlive()) {
						/*getNewComments();*/
						mCommentsList.onRefresh();
					}
				}else{
					getNewComments();
				}
				
			} else if(intent.getAction().equals(WiboMainTabActivity.NOTIFICATION_FRESH_TRANSMITS)){
				//Log.i(TAG, "BroadcastReceiver :" + WiboMainTabActivity.NOTIFICATION_FRESH_TRANSMITS);
				onClick((Button) findViewById(R.id.transmitTitleBtn));
				if (mGetNewTransmitsThread != null) {
					if (!mGetNewTransmitsThread.isAlive()) {
//						getNewTransmits();
						mTransmitsList.onRefresh();
					}
				}else{
					getNewTransmits();
				}
			}
		}
	};

	private Thread mGetNewCommentsThread = null;
    private boolean mIsGettingNewComments = false;
    private void getNewComments() {
    	if (mGetNewCommentsThread != null) {
			if (mGetNewCommentsThread.isAlive()) {
				mGetNewCommentsThread.interrupt();
			}
			mGetNewCommentsThread = null;
			mIsGettingNewComments = false;
		}
    	
    	mGetNewCommentsThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				mIsGettingNewComments = true;
				int currentScreen = mCurrentScreen;
				try {
					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_NEW_COMMENTS_ERROR, null);
							return;
						}
					}
					
					// 获取前20条
					List<Comment> comments = mWeibo.getCommentsToMe();//getCommentsToMe();
					
					if (comments.size() > 0) {
						long newestId = comments.get(0).getId();
						long the20thId = comments.get(comments.size() - 1)
								.getId();
						
						ArrayList<CommentItem> commentItemList = new ArrayList<CommentItem>();
						
						if (mNewestCommentId == -1 || (mNewestCommentId < newestId && the20thId < mNewestCommentId)) {
							boolean isInclude = false;
							// 新的20条完全包含了旧的
							if (mOldestCommentId > the20thId) {
								isInclude = true;
							}
							
							for (Comment comment : comments) {
								if (comment.getId() == mNewestCommentId && !isInclude) {
									break;
								}
								CommentItem commentItem = new CommentItem();
								commentItem.setCreatedAt(Utility.formatDate(comment.getCreatedAt()));
								commentItem.setId(comment.getId());
								commentItem.setUserId(comment.getUser().getId());
								commentItem.setSource(comment.getSource());
								commentItem.setText(comment.getText());
								commentItem.setUsername(comment.getUser().getName());
								commentItem.setWeiboUserPic(comment.getUser().getProfileImageURL().toString());
								if (Utility.isImageExist(WiboTabActivity.this, comment.getUser().getProfileImageURL().toString(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									commentItem.setmIsLoadHeadPic(true);
								}
								commentItem.setmVLogo(comment.getUser().isVerified());
								
								commentItem.setRootWeiboId(comment.getStatus().getId());
								commentItem.setRootUsername(comment.getStatus().getUser().getName());
								commentItem.setRootText(comment.getStatus().getText());
								
								commentItem.setmLatitude(String.valueOf(comment.getLatitude()));
								commentItem.setmLongitude(String.valueOf(comment.getLongitude()));
								
								commentItemList.add(commentItem);
							}
							
							if (isInclude) {
								mCommentsListData.clear();
								mCommentsListData.addAll(commentItemList);
							}else{
								// 超过60条删除旧的
								int totalSize = mCommentsListData.size()
										+ commentItemList.size();
								int originalCount = mCommentsListData.size();
								if (totalSize > MAX_SAVE_COUNT) {
									for (int i = originalCount - 1; i > originalCount - (totalSize - MAX_SAVE_COUNT) - 1; i--) {
										mCommentsListData.remove(i);
									}
									mCommentsListData.addAll(0, commentItemList);
								} else {
									mCommentsListData.addAll(0, commentItemList);
								}
							}
							mNewestCommentId = mCommentsListData.get(0).getId();
							mOldestCommentId = mCommentsListData.get(mCommentsListData.size() - 1).getId();		
						} else if (mNewestCommentId < newestId
								&& mNewestCommentId < the20thId) {
							for (Comment comment : comments) {
								CommentItem commentItem = new CommentItem();
								commentItem.setCreatedAt(Utility.formatDate(comment.getCreatedAt()));
								commentItem.setId(comment.getId());
								commentItem.setUserId(comment.getUser().getId());
								commentItem.setSource(comment.getSource());
								commentItem.setText(comment.getText());
								commentItem.setUsername(comment.getUser().getName());
								commentItem.setWeiboUserPic(comment.getUser().getProfileImageURL().toString());
								if (Utility.isImageExist(WiboTabActivity.this, comment.getUser().getProfileImageURL().toString(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									commentItem.setmIsLoadHeadPic(true);
								}
								commentItem.setmVLogo(comment.getUser().isVerified());
								
								commentItem.setRootWeiboId(comment.getStatus().getId());
								commentItem.setRootUsername(comment.getStatus().getUser().getName());
								commentItem.setRootText(comment.getStatus().getText());
								
								commentItem.setmLatitude(String.valueOf(comment.getLatitude()));
								commentItem.setmLongitude(String.valueOf(comment.getLongitude()));
								
								commentItemList.add(commentItem);
							} 
							mCommentsListData.clear();
							mCommentsListData.addAll(commentItemList);
							mNewestCommentId = mCommentsListData.get(0).getId();
							mOldestCommentId = mCommentsListData.get(mCommentsListData.size() - 1).getId();
														
						}
						if (commentItemList.size() > 0)
							sendMessage(SHOW_NEW_COMMENTS, currentScreen, commentItemList.size(), null);
						else{
							sendMessage(SHOW_NEW_COMMENTS, currentScreen, 0, null);
						}
						addCommentListToDatabase();
					}
				}catch (WeiboException e) {
					sendMessage(SHOW_NEW_COMMENTS_ERROR, e.getMessage());
					e.printStackTrace();
				} finally {
					mIsGettingNewComments = false;
				}
			}
		});
//    	if (mCommentsListData.size() == 0) {
//    		mLoadingLayout.setVisibility(LinearLayout.VISIBLE);
//    	}
    	if ((mMoreCommentThread == null || !mMoreCommentThread.isAlive()) && !isGettingFromDatabase && !mGetNewCommentsThread.isAlive()) {
    		mGetNewCommentsThread.start();
    	}
    }
    
    private Thread mMoreCommentThread = null;
	
	private void getMoreComment(final long lastId) {
		if (mMoreCommentThread != null) {
			if (mMoreCommentThread.isAlive()) {
				mMoreCommentThread.interrupt();
			}
			mMoreCommentThread = null;
		}
		mMoreCommentThread = new Thread(new Runnable() {
			
			@Override
			public synchronized void run() {
				try {
					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_BUTTOM_COMMENTS_ERROR, null);
							return;
						}
					}
					
					Paging paging = new Paging(1, 20);
					paging.setMaxId(lastId - 1);
					List<Comment> comments = null;
					comments = mWeibo.getCommentsToMe(paging);
					
					if (comments != null && comments.size() > 0) {
						// 保存第一条和最后一条微博的ID
						long newestId_2 = comments.get(0).getId();
						long the20thId_2 = comments.get(comments.size() - 1)
								.getId();
						ArrayList<CommentItem> commentItemList = new ArrayList<CommentItem>();
						
						for (Comment comment : comments) {
							CommentItem commentItem = new CommentItem();
							commentItem.setCreatedAt(Utility.formatDate(comment.getCreatedAt()));
							commentItem.setId(comment.getId());
							commentItem.setUserId(comment.getUser().getId());
							commentItem.setSource(comment.getSource());
							commentItem.setText(comment.getText());
							commentItem.setUsername(comment.getUser().getName());
							commentItem.setWeiboUserPic(comment.getUser().getProfileImageURL().toString());
							if (Utility.isImageExist(WiboTabActivity.this, comment.getUser().getProfileImageURL().toString(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
								commentItem.setmIsLoadHeadPic(true);
							}
							commentItem.setmVLogo(comment.getUser().isVerified());
							
							commentItem.setRootWeiboId(comment.getStatus().getId());
							commentItem.setRootUsername(comment.getStatus().getUser().getName());
							commentItem.setRootText(comment.getStatus().getText());
							
							commentItem.setmLatitude(String.valueOf(comment.getLatitude()));
							commentItem.setmLongitude(String.valueOf(comment.getLongitude()));
							
							commentItemList.add(commentItem);
						}
						
						if (commentItemList.size() > 0) {
							mCommentsListData.addAll(commentItemList);
							mNewestCommentId = mCommentsListData.get(0).getId();
							mOldestCommentId = mCommentsListData.get(
									mCommentsListData.size() - 1).getId();
							
							sendMessage(SHOW_BUTTOM_COMMENTS, String.valueOf(commentItemList.size()));
						}else{
							sendMessage(SHOW_BUTTOM_COMMENTS, null);
						}
												
						addCommentListToDatabase();
					}
				} catch (WeiboException e) {
					sendMessage(SHOW_BUTTOM_COMMENTS_ERROR, e.getMessage());
					e.printStackTrace();
				}
			}
		});
		if (!mMoreCommentThread.isAlive() && !isGettingFromDatabase && (mGetNewCommentsThread == null || !mGetNewCommentsThread.isAlive())) {
			mFooterProComment.setVisibility(ProgressBar.VISIBLE);
			mMoreCommentThread.start();
		}
		
	}
    
    private void addCommentListToDatabase() {
		try {
			mDbHelper.open();
			mDbHelper.deleteAllCommentListData();

			int i = 0;
			for (; i < mCommentsListData.size() && i < 60; i++) {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put(FileDbHelper.COMMENT_LIST_COMMENT_ID, mCommentsListData
						.get(i).getId());
				hashMap.put(FileDbHelper.COMMENT_LIST_USER_PIC, mCommentsListData
						.get(i).getWeiboUserPic());
				hashMap.put(FileDbHelper.COMMENT_LIST_USERNAME, mCommentsListData
						.get(i).getUsername());
				hashMap.put(FileDbHelper.COMMENT_LIST_USER_ID,
						mCommentsListData.get(i).getUserId());
				hashMap.put(FileDbHelper.COMMENT_LIST_WEIBO_TEXT, mCommentsListData
						.get(i).getText());
				hashMap.put(FileDbHelper.COMMENT_LIST_SENT_TIME, mCommentsListData
						.get(i).getCreatedAt());
				hashMap.put(FileDbHelper.COMMENT_LIST_CLIENT_NAME,
						mCommentsListData.get(i).getSource());
				hashMap.put(FileDbHelper.COMMENT_LIST_ROOT_TEXT, mCommentsListData
						.get(i).getRootText());
				hashMap.put(FileDbHelper.COMMENT_LIST_ROOT_ID, mCommentsListData
						.get(i).getRootWeiboId());
				
				hashMap.put(FileDbHelper.COMMENT_LIST_ROOT_USERNAME, mCommentsListData
						.get(i).getRootUsername());
				
				hashMap.put(FileDbHelper.COMMENT_LIST_VIP, mCommentsListData
						.get(i).ismVLogo() ? "true" : "false");

				
				hashMap.put(FileDbHelper.COMMENT_LIST_LONGITUDE, mCommentsListData
						.get(i).getmLongitude());
				hashMap.put(FileDbHelper.COMMENT_LIST_LATITUDE, mCommentsListData
						.get(i).getmLatitude());
				hashMap.put(FileDbHelper.COMMENT_LIST_ADD_DATA1, FileDbHelper.MY_COMMENT_LIST);

				mDbHelper.insertCommentListData(hashMap);
			}
			SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
			Editor editor = settings.edit();
			editor.putLong(COMMENT_NEWEST_ID, mNewestCommentId);
			editor.putLong(COMMENT_OLDEST_ID, mCommentsListData.get(i-1).getId());
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mDbHelper.close();
		}
	}
    
    private Thread mThreadGetFromDatabase = null;
	private static boolean isGettingFromDatabase = false;
	
	private void getCommentListFromDatabase() {
		if (mThreadGetFromDatabase != null) {
			if (mThreadGetFromDatabase.isAlive()) {
				mThreadGetFromDatabase.interrupt();
			}
			mThreadGetFromDatabase = null;
			isGettingFromDatabase = false;
		}
		
		mThreadGetFromDatabase = new Thread(new Runnable() {
			
			@Override
			public void run() {
				isGettingFromDatabase = true;
				int currentScreen = mCurrentScreen;
				try {
					mDbHelper.open();
					
					Cursor commentListCursor = mDbHelper.getAllCommentListData();

					final int comment_id = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_COMMENT_ID);
					final int user_pic = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_USER_PIC);
					final int username = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_USERNAME);
					final int comment_text = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_WEIBO_TEXT);
					final int user_id = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_USER_ID);
					final int sent_time = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_SENT_TIME);
					final int client_name = commentListCursor
							.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_CLIENT_NAME);
				
					final int root_text = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_ROOT_TEXT);
					final int root_weibo_id = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_ROOT_ID);
					final int root_username = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_ROOT_USERNAME);
					final int user_vip = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_VIP);

					final int longitude = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_LONGITUDE);
					final int latitude = commentListCursor
						.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_LATITUDE);
					
					final int add_data1 = commentListCursor.getColumnIndexOrThrow(FileDbHelper.COMMENT_LIST_ADD_DATA1);
					
					//commentListCursor.moveToFirst();
					commentListCursor.moveToLast();
					ArrayList<CommentItem> itemDataList = new ArrayList<CommentItem>();
					//for (int i = 0; i < commentListCursor.getCount(); i++) {
					for (int i = commentListCursor.getCount() - 1; i >= 0; i--) {
						CommentItem itemData = new CommentItem();
						if (commentListCursor.getLong(add_data1) != FileDbHelper.MY_COMMENT_LIST) {
							commentListCursor.moveToPrevious();
							continue;
						}
						itemData.setId(commentListCursor.getLong(comment_id));
						itemData.setWeiboUserPic(commentListCursor
								.getString(user_pic));
						if (Utility.isImageExist(WiboTabActivity.this, commentListCursor
								.getString(user_pic), Utility.WEIBO_PIC, Utility.USER_PIC)) {
							itemData.setmIsLoadHeadPic(true);
						}
						itemData.setUsername(commentListCursor.getString(username));
						itemData.setText(commentListCursor.getString(comment_text));
						itemData.setUserId(commentListCursor
								.getLong(user_id));
						itemData.setCreatedAt(commentListCursor.getString(sent_time));
						itemData.setSource(commentListCursor.getString(client_name));

						itemData.setRootText(commentListCursor.getString(root_text));
						itemData.setRootUsername(commentListCursor.getString(root_username));
						itemData.setRootWeiboId(commentListCursor.getLong(root_weibo_id));
						itemData.setmVLogo(commentListCursor.getString(user_vip).equalsIgnoreCase("true"));
						
						itemData.setmLongitude(commentListCursor.getString(longitude));
						itemData.setmLatitude(commentListCursor.getString(latitude));
						
						itemDataList.add(itemData);
						//commentListCursor.moveToNext();
						commentListCursor.moveToPrevious();
					}
					commentListCursor.close();
					if (itemDataList.size() > 0){
						SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
			        
						mNewestCommentId = settings.getLong(COMMENT_NEWEST_ID, -1);
						mOldestCommentId = settings.getLong(COMMENT_OLDEST_ID, -1);
		        	
						sendMessage(SHOW_COMMENT_FROM_DATABASE, currentScreen, 0, itemDataList);
					}else{
						isGettingFromDatabase = false;
						if (Utility.isNetworkAvailable(WiboTabActivity.this))
							getNewComments();
					}
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mDbHelper.close();
					isGettingFromDatabase = false;
				}
			}
		});
		
		
		if (/*!isGettingMoreWeibo && */!isGettingFromDatabase && !mIsGettingNewComments) {
			//mHeadLayout.setVisibility(RelativeLayout.VISIBLE);
			mThreadGetFromDatabase.start();
		}
	}
	
	private Thread mGetNewTransmitsThread = null;
    private boolean mIsGettingNewTransmits = false;
    private void getNewTransmits() {
    	if (mGetNewTransmitsThread != null) {
			if (mGetNewTransmitsThread.isAlive()) {
				mGetNewTransmitsThread.interrupt();
			}
			mGetNewTransmitsThread = null;
			mIsGettingNewTransmits = false;
		}
    	
    	mGetNewTransmitsThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				mIsGettingNewTransmits = true;
				int currentScreen = mCurrentScreen;
				try {
					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_NEW_TRANSMITS_ERROR, null);
							return;
						}
					}
					
					// 获取前20条
					List<Status> transmits = mWeibo.getMentions();//getTransmitsToMe();
					
					if (transmits.size() > 0) {
						long newestId = transmits.get(0).getId();
						long the20thId = transmits.get(transmits.size() - 1)
								.getId();
						
						ArrayList<WeiboItem> transmitItemList = new ArrayList<WeiboItem>();
						
						if (mNewestTransmitId == -1 || (mNewestTransmitId < newestId && the20thId < mNewestTransmitId)) {
							boolean isInclude = false;
							// 新的20条完全包含了旧的
							if (mOldestTransmitId > the20thId) {
								isInclude = true;
							}
							
							for (Status status : transmits) {
								if (status.getId() == mNewestTransmitId && !isInclude) {
									break;
								}
								WeiboItem itemData = new WeiboItem();
								itemData.setmUserName(status.getUser()
										.getName());
								itemData.setmSentTime(Utility.formatDate(status
										.getCreatedAt()));
								itemData.setmWeiboText(status.getText());
								itemData.setmClientName(status.getSource());
								itemData.setmWeiboUserPic(status.getUser()
										.getProfileImageURL().toString());
								
								if (Utility.isImageExist(WiboTabActivity.this, status.getUser()
										.getProfileImageURL().toString(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									itemData.setmIsLoadHeadPic(true);
								}
								if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
									itemData.setmWeiboPic(status.getThumbnail_pic());
									itemData.setmWeiboMidPic(status.getBmiddle_pic());
									itemData.setmWeiboLargePic(status.getOriginal_pic());
									
									if (Utility.isImageExist(WiboTabActivity.this, status.getThumbnail_pic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadWeiboPic(true);
									}
								}

								itemData.setmUserId(status.getUser().getId());
								itemData.setmVLogo(status.getUser().isVerified());
								itemData.setmLatitude(String.valueOf(status.getLatitude()));
								itemData.setmLongitude(String.valueOf(status.getLongitude()));
								
								Status transmitStatus = status.getRetweeted_status();
								if (transmitStatus != null) {
									itemData.setmRtrootText(transmitStatus.getText());
									itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
									itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
									itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
									itemData.setmRtrootWeiboId(transmitStatus.getId());
									itemData.setmRtrootUsername(transmitStatus.getUser().getName());
									itemData.setmRtrootUserId(transmitStatus.getUser().getId());
									itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
									
									if (Utility.isImageExist(WiboTabActivity.this, transmitStatus.getThumbnail_pic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadRootPic(true);
									}
								}
								itemData.setmWeiboId(status.getId());
															
								transmitItemList.add(itemData);
							}
							
							if (isInclude) {
								mTransmitsListData.clear();
								mTransmitsListData.addAll(transmitItemList);
							}else{
								// 超过60条删除旧的
								int totalSize = mTransmitsListData.size()
										+ transmitItemList.size();
								int originalCount = mTransmitsListData.size();
								if (totalSize > MAX_SAVE_COUNT) {
									for (int i = originalCount - 1; i > originalCount - (totalSize - MAX_SAVE_COUNT) - 1; i--) {
										mTransmitsListData.remove(i);
									}
									mTransmitsListData.addAll(0, transmitItemList);
								} else {
									mTransmitsListData.addAll(0, transmitItemList);
								}
							}
							mNewestTransmitId = mTransmitsListData.get(0).getmWeiboId();
							mOldestTransmitId = mTransmitsListData.get(mTransmitsListData.size() - 1).getmWeiboId();		
						} else if (mNewestTransmitId < newestId
								&& mNewestTransmitId < the20thId) {
							for (Status status : transmits) {
								WeiboItem itemData = new WeiboItem();
								itemData.setmUserName(status.getUser()
										.getName());
								itemData.setmSentTime(Utility.formatDate(status
										.getCreatedAt()));
								itemData.setmWeiboText(status.getText());
								itemData.setmClientName(status.getSource());
								itemData.setmWeiboUserPic(status.getUser()
										.getProfileImageURL().toString());
								if (Utility.isImageExist(WiboTabActivity.this, status.getUser()
										.getProfileImageURL().toString(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									itemData.setmIsLoadHeadPic(true);
								}
								if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
									itemData.setmWeiboPic(status.getThumbnail_pic());
									itemData.setmWeiboMidPic(status.getBmiddle_pic());
									itemData.setmWeiboLargePic(status.getOriginal_pic());
									
									if (Utility.isImageExist(WiboTabActivity.this, status.getThumbnail_pic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadWeiboPic(true);
									}
								}

								itemData.setmUserId(status.getUser().getId());
								itemData.setmVLogo(status.getUser().isVerified());
								itemData.setmLatitude(String.valueOf(status.getLatitude()));
								itemData.setmLongitude(String.valueOf(status.getLongitude()));
								
								Status transmitStatus = status.getRetweeted_status();
								if (transmitStatus != null) {
									itemData.setmRtrootText(transmitStatus.getText());
									itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
									itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
									itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
									itemData.setmRtrootWeiboId(transmitStatus.getId());
									itemData.setmRtrootUsername(transmitStatus.getUser().getName());
									itemData.setmRtrootUserId(transmitStatus.getUser().getId());
									itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
									
									if (Utility.isImageExist(WiboTabActivity.this, transmitStatus.getThumbnail_pic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadRootPic(true);
									}
								}
								
								itemData.setmWeiboId(status.getId());
								
								if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									itemData.setmIsLoadHeadPic(true);
								}
								
								if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
									if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadWeiboPic(true);
									}
								}
								
								if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
									if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
										if (Utility.isImageExist(WiboTabActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
											itemData.setmIsLoadRootPic(true);
										}
									}
								}
								
								transmitItemList.add(itemData);
							} 
							mTransmitsListData.clear();
							mTransmitsListData.addAll(transmitItemList);
							mNewestTransmitId = mTransmitsListData.get(0).getmWeiboId();
							mOldestTransmitId = mTransmitsListData.get(mTransmitsListData.size() - 1).getmWeiboId();
														
						}
						if (transmitItemList.size() > 0)
							sendMessage(SHOW_NEW_TRANSMITS, currentScreen, transmitItemList.size(), null);
						else{
							sendMessage(SHOW_NEW_TRANSMITS, currentScreen, 0, null);
						}
						
						addTransmitListToDatabase();
					}
				}catch (WeiboException e) {
					sendMessage(SHOW_NEW_TRANSMITS_ERROR, null);
					e.printStackTrace();
				} finally {
					mIsGettingNewTransmits = false;
				}
			}
		});
//    	if (mTransmitsListData.size() == 0) {
//    		mLoadingLayout.setVisibility(LinearLayout.VISIBLE);
//    	}
    	if (!isGettingMoreTransmit && !isGettingFromDatabase && !mIsGettingNewTransmits) {
    		mGetNewTransmitsThread.start();
    	}
    }
    
    private Thread mMoreTransmitThread = null;
	private static boolean isGettingMoreTransmit = false;
	
	private void getMoreTransmit(final long lastId) {
		if (mMoreTransmitThread != null) {
			if (mMoreTransmitThread.isAlive()) {
				mMoreTransmitThread.interrupt();
			}
			mMoreTransmitThread = null;
			isGettingMoreTransmit = false;
		}
		mMoreTransmitThread = new Thread(new Runnable() {
			
			@Override
			public synchronized void run() {
				isGettingMoreTransmit = true;
				try {
					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_BUTTOM_TRANSMITS_ERROR, null);
							return;
						}
					}
					
					Paging paging = new Paging(1, 20);
					paging.setMaxId(lastId - 1);
					List<Status> statuses = null;
					statuses = mWeibo.getMentions(paging);
					
					if (statuses != null && statuses.size() > 0) {
						// 保存第一条和最后一条微博的ID
						long newestId_2 = statuses.get(0).getId();
						long the20thId_2 = statuses.get(statuses.size() - 1)
								.getId();
						ArrayList<WeiboItem> itemDataList = new ArrayList<WeiboItem>();
						
						for (Status status : statuses) {
							WeiboItem itemData = new WeiboItem();
							itemData.setmUserName(status.getUser()
									.getName());
							itemData.setmSentTime(Utility.formatDate(status
									.getCreatedAt()));
							itemData.setmWeiboText(status.getText());
							itemData.setmClientName(status.getSource());

							itemData.setmWeiboUserPic(status.getUser()
									.getProfileImageURL().toString());
							if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
								itemData.setmWeiboPic(status.getThumbnail_pic());
								itemData.setmWeiboMidPic(status.getBmiddle_pic());
								itemData.setmWeiboLargePic(status.getOriginal_pic());
							}

							itemData.setmUserId(status.getUser().getId());
							itemData.setmVLogo(status.getUser().isVerified());
							itemData.setmLatitude(String.valueOf(status.getLatitude()));
							itemData.setmLongitude(String.valueOf(status.getLongitude()));
							
							Status transmitStatus = status.getRetweeted_status();
							if (transmitStatus != null) {
								itemData.setmRtrootText(transmitStatus.getText());
								itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
								itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
								itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
								itemData.setmRtrootWeiboId(transmitStatus.getId());
								itemData.setmRtrootUsername(transmitStatus.getUser().getName());
								itemData.setmRtrootUserId(transmitStatus.getUser().getId());
								itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
							}
							itemData.setmWeiboId(status.getId());
							
							if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
								itemData.setmIsLoadHeadPic(true);
							}
							
							if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
								if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
									itemData.setmIsLoadWeiboPic(true);
								}
							}
							
							if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
								if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
									if (Utility.isImageExist(WiboTabActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadRootPic(true);
									}
								}
							}
							
							itemDataList.add(itemData);
						}
						
						if (itemDataList.size() > 0) {
							mTransmitsListData.addAll(itemDataList);
							mNewestTransmitId = mTransmitsListData.get(0).getmWeiboId();
							mOldestTransmitId = mTransmitsListData.get(
									mTransmitsListData.size() - 1).getmWeiboId();
							
							sendMessage(SHOW_BUTTOM_TRANSMITS, String.valueOf(itemDataList.size()));
						}else{
							sendMessage(SHOW_BUTTOM_TRANSMITS, null);
						}
						
						// 获取评论和转发数
						int leftSize = mTransmitsListData.size();
						List<Count> counts = null;
						int i = 0;
						int j = 0;
						int startIndex = 0;
						String ids = "";
						if (leftSize > WiboMainActivity.GET_COUNT_MAX) {
							do {
								for (; i < startIndex + WiboMainActivity.GET_COUNT_MAX; i++) {
									ids += String.valueOf(mTransmitsListData.get(i).getmWeiboId()) + ",";
								}
								ids = ids.substring(0, ids.length() - 1);

								counts = mWeibo.getCounts(ids);
								
								if (counts != null) {
									for (Count count : counts) {
										for (j = 0; j < mTransmitsListData.size(); j++) {
											if (mTransmitsListData.get(j).getmWeiboId() == count.getId()){
												mTransmitsListData.get(j).setmCommentCount(String.valueOf(count.getComments()));
												mTransmitsListData.get(j).setmTransmitCount(String.valueOf(count.getRt()));
												break;
											}
										}
									}
								}
								startIndex += WiboMainActivity.GET_COUNT_MAX;
							} while ((leftSize -= WiboMainActivity.GET_COUNT_MAX) > WiboMainActivity.GET_COUNT_MAX);
						}
						
						if (leftSize > 0 && leftSize <= WiboMainActivity.GET_COUNT_MAX) {
							ids = "";
							for (; i < mTransmitsListData.size(); i++) {
								ids += String.valueOf(mTransmitsListData.get(i).getmWeiboId()) + ",";
							}
							ids = ids.substring(0, ids.length() - 1);

							counts = mWeibo.getCounts(ids);
							
							if (counts != null) {
								for (Count count : counts) {									
									for (j = 0; j < mTransmitsListData.size(); j++) {
										if (mTransmitsListData.get(j).getmWeiboId() == count.getId()){
											mTransmitsListData.get(j).setmCommentCount(String.valueOf(count.getComments()));
											mTransmitsListData.get(j).setmTransmitCount(String.valueOf(count.getRt()));
											break;
										}
									}
								}
							}
						}
						
						sendMessage(REFRESH_TRANSMIT_LIST, null);
						
						addTransmitListToDatabase();
					}
				} catch (WeiboException e) {
					sendMessage(SHOW_BUTTOM_TRANSMITS_ERROR, e.getMessage());
					e.printStackTrace();
				} finally {
					isGettingMoreTransmit = false;
				}
			}
		});
		if (!isGettingMoreTransmit && !isGettingTranFromDB && !mIsGettingNewTransmits) {
			mFooterProTransmit.setVisibility(ProgressBar.VISIBLE);
			mMoreTransmitThread.start();
		}
		
	}
    
    private void addTransmitListToDatabase() {
		try {
			mDbHelper.open();
			mDbHelper.deleteAllTransmitListData();
			//int count = mItemDataList.size() > 60 ? 60 : mItemDataList.size();
			int i = 0;
			for (/*int i = count - 1*/; /*i >= 0*/i < mTransmitsListData.size() && i < MAX_SAVE_COUNT; i++) {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_ID, mTransmitsListData
						.get(i).getmWeiboId());
				hashMap.put(FileDbHelper.WEIBO_LIST_USER_PIC, mTransmitsListData
						.get(i).getmWeiboUserPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_PIC, mTransmitsListData
						.get(i).getmWeiboPic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_MID_PIC, mTransmitsListData
						.get(i).getmWeiboMidPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_LARGE_PIC, mTransmitsListData
						.get(i).getmWeiboLargePic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_ORIGINAL_WEIBO_PIC,
						mTransmitsListData.get(i).getmRtrootWeiboPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_MID_PIC, mTransmitsListData
						.get(i).getmRtrootWeiboMidPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_LARGE_PIC, mTransmitsListData
						.get(i).getmRtrootWeiboLargePic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_USERNAME, mTransmitsListData
						.get(i).getmUserName());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_TEXT, mTransmitsListData
						.get(i).getmWeiboText());
				hashMap.put(FileDbHelper.WEIBO_LIST_ORIGINAL_TEXT,
						mTransmitsListData.get(i).getmRtrootText());
				hashMap.put(FileDbHelper.WEIBO_LIST_SENT_TIME, mTransmitsListData
						.get(i).getmSentTime());
				hashMap.put(FileDbHelper.WEIBO_LIST_CLIENT_NAME, mTransmitsListData
						.get(i).getmClientName());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_USER_ID, mTransmitsListData
						.get(i).getmUserId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_USERNAME, mTransmitsListData
						.get(i).getmRtrootUsername());
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_WEIBO_ID, mTransmitsListData
						.get(i).getmRtrootWeiboId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_VIP, mTransmitsListData
						.get(i).ismVLogo() ? "true" : "false");
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_UID, mTransmitsListData
						.get(i).getmRtrootUserId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_VIP, mTransmitsListData
						.get(i).ismRtrootVLogo() ? "true" : "false");
				
				hashMap.put(FileDbHelper.WEIBO_LIST_LONGITUDE, mTransmitsListData
						.get(i).getmLongitude());
				hashMap.put(FileDbHelper.WEIBO_LIST_LATITUDE, mTransmitsListData
						.get(i).getmLatitude());
				hashMap.put(FileDbHelper.WEIBO_LIST_ADD_DATA1, FileDbHelper.MY_TRANSMIT_LIST);

				hashMap.put(FileDbHelper.WEIBO_LIST_COMMENT_COUNT,
						mTransmitsListData.get(i).getmCommentCount());
				hashMap.put(FileDbHelper.WEIBO_LIST_TRANSMIT_COUNT,
						mTransmitsListData.get(i).getmTransmitCount());
				mDbHelper.insertTransmitListData(hashMap);
			}
			SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
			Editor editor = settings.edit();
			editor.putLong(TRANSMIT_NEWEST_ID, mNewestTransmitId);
			editor.putLong(TRANSMIT_OLDEST_ID, mTransmitsListData.get(i-1).getmWeiboId());
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mDbHelper.close();
		}
	}

	private Thread mThreadGetTranFromDB = null;
	private static boolean isGettingTranFromDB = false;
	
	private void getTransmitListFromDatabase() {
		mThreadGetTranFromDB = new Thread(new Runnable() {
			
			@Override
			public void run() {
				isGettingTranFromDB = true;
				try {
					mDbHelper.open();
					
					Cursor weiboListCursor = mDbHelper.getAllTransmitListData();

					final int weib_id = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_ID);
					final int user_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_PIC);
					final int weibo_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_PIC);
					final int weibo_mid_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_MID_PIC);
					final int weibo_large_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_LARGE_PIC);
					final int original_weibo_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_WEIBO_PIC);
					final int root_weibo_mid_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_MID_PIC);
					final int root_weibo_large_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_LARGE_PIC);
					final int username = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USERNAME);
					final int weibo_text = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_TEXT);
					final int original_text = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_TEXT);
					final int sent_time = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_SENT_TIME);
					final int client_name = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_CLIENT_NAME);
					final int comment_count = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_COMMENT_COUNT);
					final int transmit_count = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_TRANSMIT_COUNT);
					
					final int user_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_ID);
					final int root_username = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_USERNAME);
					final int root_weibo_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_WEIBO_ID);
					final int user_vip = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_VIP);
					final int root_user_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_UID);
					final int root_user_vip = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_VIP);
					final int longitude = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LONGITUDE);
					final int latitude = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LATITUDE);
					
					final int add_data1 = weiboListCursor.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ADD_DATA1);
					
					//weiboListCursor.moveToFirst();
					weiboListCursor.moveToLast();
					ArrayList<WeiboItem> itemDataList = new ArrayList<WeiboItem>();
					//for (int i = 0; i < weiboListCursor.getCount(); i++) {
					for (int i = weiboListCursor.getCount() - 1; i >= 0; i--) {
						WeiboItem itemData = new WeiboItem();
						if (weiboListCursor.getLong(add_data1) != FileDbHelper.MY_TRANSMIT_LIST) {
							weiboListCursor.moveToPrevious();
							continue;
						}
						itemData.setmWeiboId(weiboListCursor.getLong(weib_id));
						itemData.setmWeiboUserPic(weiboListCursor.getString(user_pic));
						itemData.setmWeiboPic(weiboListCursor.getString(weibo_pic));
						itemData.setmWeiboMidPic(weiboListCursor.getString(weibo_mid_pic));
						itemData.setmWeiboLargePic(weiboListCursor.getString(weibo_large_pic));
						itemData.setmRtrootWeiboPic(weiboListCursor
								.getString(original_weibo_pic));
						itemData.setmRtrootWeiboMidPic(weiboListCursor.getString(root_weibo_mid_pic));
						itemData.setmRtrootWeiboLargePic(weiboListCursor.getString(root_weibo_large_pic));
						itemData.setmUserName(weiboListCursor.getString(username));
						itemData.setmWeiboText(weiboListCursor.getString(weibo_text));
						itemData.setmRtrootText(weiboListCursor
								.getString(original_text));
						itemData.setmSentTime(weiboListCursor.getString(sent_time));
						itemData.setmClientName(weiboListCursor.getString(client_name));
						itemData.setmCommentCount(weiboListCursor
								.getString(comment_count));
						itemData.setmTransmitCount(weiboListCursor
								.getString(transmit_count));
						itemData.setmUserId(weiboListCursor.getLong(user_id));
						itemData.setmRtrootUsername(weiboListCursor.getString(root_username));
						itemData.setmRtrootWeiboId(weiboListCursor.getLong(root_weibo_id));
						itemData.setmVLogo(weiboListCursor.getString(user_vip).equalsIgnoreCase("true"));
						itemData.setmRtrootUserId(weiboListCursor.getLong(root_user_id));
						itemData.setmRtrootVLogo(weiboListCursor.getString(root_user_vip).equalsIgnoreCase("true"));
						itemData.setmLongitude(weiboListCursor.getString(longitude));
						itemData.setmLatitude(weiboListCursor.getString(latitude));
				
						if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
							itemData.setmIsLoadHeadPic(true);
						}
						
						if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
							if (Utility.isImageExist(WiboTabActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
								itemData.setmIsLoadWeiboPic(true);
							}
						}
						
						if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
							if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
								if (Utility.isImageExist(WiboTabActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
									itemData.setmIsLoadRootPic(true);
								}
							}
						}
						
						itemDataList.add(itemData);
						//weiboListCursor.moveToNext();
						weiboListCursor.moveToPrevious();
					}
					weiboListCursor.close();
					if (itemDataList.size() > 0){
						SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
			        
						mNewestTransmitId = settings.getLong(TRANSMIT_NEWEST_ID, -1);
						mOldestTransmitId = settings.getLong(TRANSMIT_OLDEST_ID, -1);
			        	
//			        	mTransmitsListData.clear();
//			        	mTransmitsListData.addAll(itemDataList);
//			        	
						sendMessage(SHOW_TRANSMIT_FROM_DATABASE, itemDataList);
					}
					else
						getNewTransmits();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mDbHelper.close();
					isGettingTranFromDB = false;
				}
			}
		});
		
		
		if (/*!isGettingMoreWeibo && */!isGettingTranFromDB) {
			//mHeadLayout.setVisibility(RelativeLayout.VISIBLE);
			mThreadGetTranFromDB.start();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > WiboMainActivity.FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > WiboMainActivity.FLING_MIN_VELOCITY) {

		} else if (e2.getX() - e1.getX() > WiboMainActivity.FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > WiboMainActivity.FLING_MIN_VELOCITY && Math.abs(e2.getY() - e1.getY()) < 30 && mCurrentScreen == 0) {
			
			// 切换Activity
//			Intent intent = new Intent(WiboTabActivity.this,
//					WiboMainActivity.class);
//			startActivity(intent);
			((TabActivity)getParent()).getTabHost().setCurrentTab(0);
		}

		return false;
	}
	
	private Thread mGetCommentPicThread = null;

	
	public void loadImageDrawable(int screenIndex, final int startIndex) {
		switch (screenIndex) {
		case TYPE_ALL:
			if(startIndex < mCommentsListData.size() ){
				
				int lastIndex = mCommentsListData.size() - 1;
				if(lastIndex - startIndex > DOWNLOAD_IMAGE_MAX_SIZE) {
					lastIndex = startIndex + DOWNLOAD_IMAGE_MAX_SIZE;
				}
				loadCommentPic(startIndex, lastIndex);
			}
			break;
		case TYPE_FREE:
			if(startIndex < mTransmitsListData.size() ){
				
				int lastIndex = mTransmitsListData.size() - 1;
				if(lastIndex - startIndex > DOWNLOAD_IMAGE_MAX_SIZE) {
					lastIndex = startIndex + DOWNLOAD_IMAGE_MAX_SIZE;
				}
				loadTransmitPic(startIndex, lastIndex);
			}
			break;
//		case TYPE_PAY:
//			if(startIndex < mPrivateListData.size() ){
//				
//				int lastIndex = mCommentsListData.size() - 1;
//				if(lastIndex - startIndex > DOWNLOAD_IMAGE_MAX_SIZE) {
//					lastIndex = startIndex + DOWNLOAD_IMAGE_MAX_SIZE;
//				}
//				loadCommentPic(startIndex, lastIndex);
//			}
//			break;
		}
		
	}
	
	private void loadCommentPic(final int startIndex, final int lastIndex) {
		
		if (mGetCommentPicThread != null) {
			if (mGetCommentPicThread.isAlive()) {
				mGetCommentPicThread.interrupt();
			}
			mGetCommentPicThread = null;
		}
		
		mGetCommentPicThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
				
				for (int i = startIndex; lastIndex < mCommentsListData.size() && i < lastIndex; i++) {
					String path = Utility.getImagePath(WiboTabActivity.this,mCommentsListData.get(i).getWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC);
			
					if (path != null) {
						mCommentsListData.get(i).setmIsLoadHeadPic(true);
					}
				}
				sendMessage(REFRESH_COMMENT_LIST, null);
			}
		});
		mGetCommentPicThread.start();
	}
	
	private Thread mGetTransmitPicThread = null;
	
	private void loadTransmitPic(final int startIndex, final int lastIndex) {
		if (mGetTransmitPicThread != null) {
			if (mGetTransmitPicThread.isAlive()) {
				mGetTransmitPicThread.interrupt();
			}
			mGetTransmitPicThread = null;
		}
		
		mGetTransmitPicThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
				
				int size = mTransmitsListData.size();
				for (int i = startIndex; lastIndex < size && i < lastIndex; i++) {
					String path = Utility.getImagePath(WiboTabActivity.this, mTransmitsListData.get(i).getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC);
			
					if (path != null) {
						mTransmitsListData.get(i).setmIsLoadHeadPic(true);
					}
					
					if (mTransmitsListData.get(i).getmWeiboPic() != null && !mTransmitsListData.get(i).getmWeiboPic().isEmpty()){
						path = Utility.getImagePath(WiboTabActivity.this, mTransmitsListData.get(i).getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC);
						if (path != null) {
							mTransmitsListData.get(i).setmIsLoadWeiboPic(true);
						}
					}
					
					if (mTransmitsListData.get(i).getmRtrootText() != null && !mTransmitsListData.get(i).getmRtrootText().isEmpty()) {
						if (mTransmitsListData.get(i).getmRtrootWeiboPic() != null && !mTransmitsListData.get(i).getmRtrootWeiboPic().isEmpty()){
							path = Utility.getImagePath(WiboTabActivity.this, mTransmitsListData.get(i).getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC);
							if (path != null) {
								mTransmitsListData.get(i).setmIsLoadRootPic(true);
							}
						}
					}
				}
				sendMessage(REFRESH_TRANSMIT_LIST, null);
			}
		});
		mGetTransmitPicThread.start();
	}
	
	public static final int DOWNLOAD_IMAGE_MAX_SIZE = 5;
	
	// 记录上次获取图片信息的时间
	private int mLastFreshCommentImageIndex = 0;
	private int mLastFreshTransmitImageIndex = 0;
	
	
	private void refreshCommentImageForList(int viewId){
		if(mCommentsListData != null && mCommentsListData.size() > 0){
			int startIndex = mCommentsList.getFirstVisiblePosition();
			int endIndex = mCommentsList.getLastVisiblePosition();
			
			// 设置上一次的刷新位置
			mLastFreshCommentImageIndex = startIndex;
			
			if(startIndex > 0){
				--startIndex;
			}
			if(endIndex >= mCommentsListData.size()){
				endIndex = mCommentsListData.size() - 1;
			}
			
			for (int i = startIndex; i <= endIndex; i++) {
				if (!mCommentsListData.get(i).ismIsLoadHeadPic()){
					loadCommentPic(i, endIndex);
					return;
				}
			}
		}
	}
	
	private void refreshTransmitImageForList(int viewId){
		if(mTransmitsListData != null && mTransmitsListData.size() > 0){
			int startIndex = mTransmitsList.getFirstVisiblePosition();
			int endIndex = mTransmitsList.getLastVisiblePosition();
			
			// 设置上一次的刷新位置
			mLastFreshTransmitImageIndex = startIndex;
			
			if(startIndex > 0){
				--startIndex;
			}
			if(endIndex >= mTransmitsListData.size()){
				endIndex = mTransmitsListData.size() - 1;
			}
			
			for (int i = startIndex; i <= endIndex; i++) {
				if (!mTransmitsListData.get(i).ismIsLoadHeadPic() || 
						(mTransmitsListData.get(i).getmWeiboPic() != null && !mTransmitsListData.get(i).ismIsLoadWeiboPic()) ||
						(mTransmitsListData.get(i).getmRtrootWeiboPic() != null && !mTransmitsListData.get(i).ismIsLoadRootPic())){
					loadTransmitPic(i, endIndex);
					return;
				}
			}
		}
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		switch (view.getId()) {
		case R.id.commentsList:
			if(Math.abs(firstVisibleItem - mLastFreshCommentImageIndex) >= DOWNLOAD_IMAGE_MAX_SIZE){
				refreshCommentImageForList(view.getId());
			}
			break;
		case R.id.transmitsList:
			if(Math.abs(firstVisibleItem - mLastFreshTransmitImageIndex) >= DOWNLOAD_IMAGE_MAX_SIZE){
				refreshTransmitImageForList(view.getId());
			}
			break;
//		case TYPE_PAY:
//			break;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(scrollState == SCROLL_STATE_IDLE){
			switch (mCurrentScreen) {
			case TYPE_ALL:
				refreshCommentImageForList(view.getId());
				break;
			case TYPE_FREE:
				refreshTransmitImageForList(view.getId());
				break;
//			case TYPE_PAY:
//				break;
			}
			
		}
	}

	@Override
	public void onSelected(int selectedIndex) {
		switch (selectedIndex) {
		case 0:
//			if (mCurrentScreen == TYPE_ALL) {
//				((TabActivity)getParent()).getTabHost().setCurrentTab(0);
//			}
			
			if(mCurrentScreen != TYPE_ALL){
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
//				mNoResultText.setVisibility(View.GONE);
				if (mCurrentScreen == TYPE_FREE){
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_21);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}else{
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_12);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}
				
				SetTypeLayoutVisible(TYPE_ALL);
				if (mCommentsListData.size() == 0/* && mTotalCountAll < 0 && !mbLoadingAll*/) {
//					if(mStoreManager.isLoadAccessToken()){
					getCommentListFromDatabase();
				}
//				}else{
					setUiShow(TYPE_ALL, /*mbLoadingAll, */false);
//				}
			}
			break;
		case 1:
			if(mCurrentScreen != TYPE_FREE){
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
//				mNoResultText.setVisibility(View.GONE);
				if (mCurrentScreen == TYPE_ALL){
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_12);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}else{
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_21);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}
				SetTypeLayoutVisible(TYPE_FREE);

				if (mTransmitsListData.size() == 0/* & mTotalCountFree < 0 && !mbLoadingFree*/) {
					getTransmitListFromDatabase();
				}
//				}else{
					setUiShow(TYPE_FREE, /*mbLoadingFree, */false);
//				}
			}
			break;
//		case 2:
//			if(mCurrentScreen != TYPE_PAY){
//				if (mCurrentScreen == TYPE_FREE){
//					//创建Animation对象  
//					Animation animation = AnimationUtils.loadAnimation(  
//					getApplicationContext(), R.anim.apphead23);  
//					animation.setFillAfter(true);
//					//组件播放动画  
//					mScrollbarTipLayout.startAnimation(animation); 
//				}else{
//					//创建Animation对象  
//					Animation animation = AnimationUtils.loadAnimation(  
//					getApplicationContext(), R.anim.apphead13);  
//					animation.setFillAfter(true);
//					//组件播放动画  
//					mScrollbarTipLayout.startAnimation(animation); 
//				}
//				
//				SetTypeLayoutVisible(TYPE_PAY);
//				setUiShow(TYPE_PAY, /*mbLoadingPay, */false);
//			}
//			break;
		}
	}
	
	// 设置哪个列表头需要显示,同时清空临时数据
    private void SetTypeLayoutVisible(int type){
    	
    	// 清除临时数据
		mCurrentScreen = type;
		
        switch(type){
    	case TYPE_ALL:
    		mListContentView.showScreen(0);
    		mCommentsList.setVisibility(View.VISIBLE);
            mTransmitsList.setVisibility(View.INVISIBLE);
            //mPrivateList.setVisibility(View.INVISIBLE);
			break;
    	case TYPE_FREE:
    		mListContentView.showScreen(1);
    		mCommentsList.setVisibility(View.INVISIBLE);
    		mTransmitsList.setVisibility(View.VISIBLE);
    		//mPrivateList.setVisibility(View.INVISIBLE);
    		break;
//    	case TYPE_PAY:
//    		mListContentView.showScreen(2);
//    		mCommentsList.setVisibility(View.INVISIBLE);
//    		mTransmitsList.setVisibility(View.INVISIBLE);
//    		mPrivateList.setVisibility(View.VISIBLE);
//    		break;
    	}
    }

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId()){
		case R.id.commentTitleBtn:
			if(mCurrentScreen != TYPE_ALL){
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
//				mNoResultText.setVisibility(View.GONE);
				if (mCurrentScreen == TYPE_FREE){
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_21);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}else{
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_12);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}
				SetTypeLayoutVisible(TYPE_ALL);
				
				setUiShow(TYPE_ALL, /*mbLoadingAll, */false);
				if (mCommentsListData.size() == 0/* && mTotalCountAll < 0 && !mbLoadingAll*/) {
					getCommentListFromDatabase();
				}
				
			}			
			break;
		case R.id.transmitTitleBtn:
			if(mCurrentScreen != TYPE_FREE){
//				mLoadingLayout.setVisibility(LinearLayout.GONE);
//				mNoResultText.setVisibility(View.GONE);
				if (mCurrentScreen == TYPE_ALL){
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_12);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}else{
					//创建Animation对象  
					Animation animation = AnimationUtils.loadAnimation(  
					getApplicationContext(), R.anim.total_2_21);  
					animation.setFillAfter(true);
					//组件播放动画  
					mScrollbarTipLayout.startAnimation(animation); 
				}
				SetTypeLayoutVisible(TYPE_FREE);

				setUiShow(TYPE_FREE, /*mbLoadingFree, */false);

				if (mTransmitsListData.size() == 0/* & mTotalCountFree < 0 && !mbLoadingFree*/) {
					getTransmitListFromDatabase();
				}	
			}
			break;
//		case R.id.privateTitleBtn:
//			if(mCurrentScreen != TYPE_PAY){
//				if (mCurrentScreen == TYPE_FREE){
//					//创建Animation对象  
//					Animation animation = AnimationUtils.loadAnimation(  
//					getApplicationContext(), R.anim.apphead23);  
//					animation.setFillAfter(true);
//					//组件播放动画  
//					mScrollbarTipLayout.startAnimation(animation); 
//				}else{
//					//创建Animation对象  
//					Animation animation = AnimationUtils.loadAnimation(  
//					getApplicationContext(), R.anim.apphead13);  
//					animation.setFillAfter(true);
//					//组件播放动画  
//					mScrollbarTipLayout.startAnimation(animation); 
//				}
//				
//				SetTypeLayoutVisible(TYPE_PAY);
////				if (mDatasPay.size() == 0 && mTotalCountPay < 0 && !mbLoadingPay) {
////					if(mStoreManager.isLoadAccessToken()){
////						getAppPay();
////					}
////				}else{
//					setUiShow(TYPE_PAY, /*mbLoadingPay,*/ false);
////				}
//			}
//			break;
		}
	}
	// 根据状态设置总的UI显示情况(不包括设置三个分类的layout中哪个layout显示,即type已经标志了当前显示的layout)
	private void setUiShow(int type, /*boolean bWaiting, */boolean bError){
		if(mCurrentScreen == type){
			//ArrayList<MStoreAppListItem> dataList;
			if(type == TYPE_ALL){
				mTextViewComment.setSelected(true);
				mTextViewTransmits.setSelected(false);
				//mTextViewPrivate.setSelected(false);
			}else{
				if(type == TYPE_FREE){
					mTextViewComment.setSelected(false);
					mTextViewTransmits.setSelected(true);
					//mTextViewPrivate.setSelected(false);
				}
			}	
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch (arg0.getId()) {
		case R.id.commentsList:
			showCommentItemDialog(arg2 - 1);
			break;
		case R.id.transmitsList:
			Intent intent = new Intent(WiboTabActivity.this, WeiboDetailsActivity.class);
			Bundle bundle = new Bundle();
    		bundle.putLong("weiboId", mTransmitsListData.get(arg2 - 1).getmWeiboId());
    		bundle.putSerializable("weiboItem", mTransmitsListData.get(arg2 - 1));
			intent.putExtras(bundle);
			startActivity(intent);
			
			break;
		default:
			break;
		}
	}
	
	private void showCommentItemDialog(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WiboTabActivity.this);
		builder.setTitle(R.string.weiboOperation);
		builder.setItems(R.array.myCommentItem_ary, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (pos >= mCommentsListData.size() || pos < 0){
					return;
				}
            	switch (which) {
            	case 0:					
					Intent intent = new Intent(WiboTabActivity.this, SendWeiboActivity.class);
            		Bundle bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.COMMENT_COMMENT);
            		bundle.putLong("commentId", mCommentsListData.get(pos).getId());
            		bundle.putLong("weiboId", mCommentsListData.get(pos).getRootWeiboId());
            		bundle.putString("username", mCommentsListData.get(pos).getUsername());
            		bundle.putString("text", mCommentsListData.get(pos).getText());

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	
            	case 1:
            		intent = new Intent(WiboTabActivity.this, WiboUserDetailsActivity.class);
        			bundle = new Bundle();
            		bundle.putLong("userId", mCommentsListData.get(pos).getUserId());
            		intent.putExtras(bundle);
        			startActivity(intent);
            		break;
            	case 2:
            		intent = new Intent(WiboTabActivity.this, WeiboDetailsActivity.class);
    	    		bundle = new Bundle();
    	    		bundle.putLong("weiboId", mCommentsListData.get(pos).getRootWeiboId());
    				intent.putExtras(bundle);
    				startActivity(intent);
            		break;
            	case 3:
            		ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            		//clip.getText();    // 粘贴
            		clip.setText(mCommentsListData.get(pos).getText());
            		Toast.makeText(WiboTabActivity.this, getString(R.string.copySuc), Toast.LENGTH_SHORT).show();
            		break;
            	}
            	
			}
		});
		
		builder.show();
	}
	
	private void showTransmitItemDialog(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WiboTabActivity.this);
		builder.setTitle(R.string.weiboOperation);
		builder.setItems(R.array.myTranItem_ary, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (pos >= mTransmitsListData.size() || pos < 0){
					return;
				}
            	switch (which) {
            	case 0:
            		Intent intent = new Intent(WiboTabActivity.this, SendWeiboActivity.class);
            		Bundle bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.REPLY_COMMENT);
            		bundle.putLong("weiboId", mTransmitsListData.get(pos).getmWeiboId());
            		bundle.putString("username", mTransmitsListData.get(pos).getmUserName());
            		bundle.putString("text", mTransmitsListData.get(pos).getmWeiboText());

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	case 1:
            		intent = new Intent(WiboTabActivity.this, SendWeiboActivity.class);
            		bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.TRANSMIT_WEIBO);
            		bundle.putLong("weiboId", mTransmitsListData.get(pos).getmWeiboId());
            		bundle.putString("username", mTransmitsListData.get(pos).getmUserName());
            		bundle.putString("text", mTransmitsListData.get(pos).getmWeiboText());
            		if (mTransmitsListData.get(pos).getmRtrootText() != null){
            			bundle.putString("rootText", mTransmitsListData.get(pos).getmRtrootText());
            			bundle.putString("rootUsername", mTransmitsListData.get(pos).getmRtrootUsername());
            		}

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	case 2:
            		intent = new Intent(WiboTabActivity.this, WeiboDetailsActivity.class);
    	    		bundle = new Bundle();
    	    		bundle.putLong("weiboId", mTransmitsListData.get(pos).getmWeiboId());
    	    		bundle.putSerializable("weiboItem", mTransmitsListData.get(pos));
    				intent.putExtras(bundle);
    				startActivity(intent);
            		break;
            	case 3:
            		ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            		//clip.getText();    // 粘贴
            		clip.setText(mTransmitsListData.get(pos).getmWeiboText());
            		Toast.makeText(WiboTabActivity.this, getString(R.string.copySuc), Toast.LENGTH_SHORT).show();
            		break;
            	case 4:
            		intent = new Intent(WiboTabActivity.this, WiboUserDetailsActivity.class);
        			bundle = new Bundle();
            		bundle.putLong("userId", mTransmitsListData.get(pos).getmUserId());
            		intent.putExtras(bundle);
        			startActivity(intent);
            		
            		break;
            	}
            	
			}
		});
		
		builder.show();
	}
}
